package com.kuafu.latte.exchange;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class ByteUtil {
    /**
     * 对象转byte
     *
     * @param obj
     * @return
     */
    public static byte[] objectToByte(Object obj) throws Exception {
        /*byte[] bytes = null;
        // object to bytearray
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);
        bytes = bo.toByteArray();
        bo.close();
        oo.close(); */
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //Hessian的序列化输出
        HessianOutput ho = new HessianOutput(os);
        try{
            ho.writeObject(obj);
            byte[] bytes = os.toByteArray();
            return bytes;
        }finally {
            os.close();
            ho.close();
        }
    }

    /**
     * byte转对象
     *
     * @param bytes
     * @return
     */
    public static Object byteToObject(byte[] bytes) throws Exception {
        /*Object obj = null;
        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
        ObjectInputStream oi = new ObjectInputStream(bi);
        obj = oi.readObject();
        bi.close();
        oi.close();*/
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        //Hessian的反序列化读取对象
        HessianInput hi = new HessianInput(is);
        try{
            Object obj = hi.readObject();
            return obj;
        }finally {
            is.close();
            hi.close();
        }
    }
}
